package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class PublicTimeline extends Activity {

	private static final int ID_REFRESH = 1;
	private static final int GROUP1 = 0;
	DefaultHttpClient httpclient;
	String username,password;
	private GetTimelineTask timelineTask;
	ArrayList<String> timelinePhotos;
	boolean threadRunning = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"PublicTimeline : onCreate");
		setContentView(R.layout.publictimeline);

		httpclient = new DefaultHttpClient();
		Cookie cookie = Common.recupCookie(this);
		httpclient.getCookieStore().addCookie(cookie);
		httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);

		Bundle bundle = getIntent().getExtras();
		username = bundle.getString("username");
		password = bundle.getString("password");

		if(savedInstanceState==null){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"Downloading public timeline");
			findViewById(R.id.publicLoadingLinear).setVisibility(View.VISIBLE);
			timelineTask = new GetTimelineTask();
			timelineTask.setActivity(this);
			timelineTask.execute();
		}else{
			if(getLastNonConfigurationInstance()!=null){
				timelineTask=(GetTimelineTask) getLastNonConfigurationInstance();
				timelineTask.setActivity(this);
			}else{
				timelinePhotos = savedInstanceState.getStringArrayList("timelinePhotos");
				if(timelinePhotos!=null && timelinePhotos.size()>0) 
					displayPhotos(true);
				else
					displayPhotos(false);
			}			
		}
	}

	protected void onSaveInstanceState(Bundle outState) {
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"PublicTimeline : onSaveInstantState");
		outState.putStringArrayList("timelinePhotos",timelinePhotos);
	}

	public Object onRetainNonConfigurationInstance() {
		if(timelineTask!=null){
			timelineTask.setActivity(null);
		}
		return timelineTask;
	}

	private void fillTimelineArray(String reponse){
		timelinePhotos = new ArrayList<String>();
		try {
			JSONArray jTimeline = new JSONArray(reponse);
			if(jTimeline.length()==0)
				displayPhotos(false);
			else{
				for(int i=0;i<jTimeline.length();i++){
					timelinePhotos.add(jTimeline.getString(i));
				}
				displayPhotos(true);
			}
		} catch (JSONException e) {
			displayPhotos(false);
		}
	}

	private void displayPhotos(boolean photosOK){
		findViewById(R.id.publicLoadingLinear).setVisibility(View.GONE);
		if(photosOK){
			findViewById(R.id.listPublicPhotos).setVisibility(View.VISIBLE);
			findViewById(R.id.errorTimeline).setVisibility(View.GONE);
			ListView timelineList = (ListView)findViewById(R.id.listPublicPhotos);
			PublicTimelineAdapter adapterTimeline = new PublicTimelineAdapter(this,timelinePhotos);
			timelineList.setAdapter(adapterTimeline);
			setOnClickPhotos(timelineList);
		}else{
			findViewById(R.id.errorTimeline).setVisibility(View.VISIBLE);
		}
	}

	private void setOnClickPhotos(ListView timelineList){
		timelineList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
				JSONObject jPicture;
				try {
					jPicture = new JSONObject(timelinePhotos.get(position));
					String photoURL = Common.getBaseImgsUrl()+jPicture.getString("url");
					Intent i = new Intent(PublicTimeline.this,FullscreenPicture.class);
					i.putExtra("uri", photoURL);
					startActivity(i);
				} catch (JSONException e) {
				}
			}
		});
	}

	private void onThreadCompleted(Bundle data){
		if(!data.containsKey("eMessage")){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"onThreadCompleted");
			fillTimelineArray(data.getString("reponse"));
		}else{
			Toast erreurToast = Toast.makeText(PublicTimeline.this,data.getString("eMessage"),Toast.LENGTH_SHORT);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
		setThreadRunning(false);
	}

	private class GetTimelineTask extends AsyncTask<String,String,Message>{
		private PublicTimeline activity;
		private boolean completed=false;
		private Message msg;

		protected Message doInBackground(String... parameters) {
			Message msg = Message.obtain();
			Bundle data = new Bundle();
			String urlTimeline = Common.getBaseUrl()+"/timeline";
			String reponse = null;
			setThreadRunning(true);
			try {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("user", username));
				params.add(new BasicNameValuePair("password", password));
				reponse = Common.postUrlData(httpclient, urlTimeline,params);
				data.putString("reponse",reponse);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			completed=true;
			this.msg=msg;
			if(activity!=null)
				endTask(msg);
		}

		private void setActivity(PublicTimeline activity) {
			this.activity = activity;
			if ( completed ) {
				endTask(msg);
			}
		}

		private void endTask(Message msg){
			activity.timelineTask=null;
			activity.onThreadCompleted(msg.getData());
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(GROUP1, ID_REFRESH, 0, getString(R.string.refresh)).setIcon(R.drawable.ic_menu_refresh);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		super.onPrepareOptionsMenu(menu);

		MenuItem item = menu.findItem(ID_REFRESH);
		if(isThreadRunning()){
			item.setEnabled(false);
		}
		else{
			item.setEnabled(true);
		}
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ID_REFRESH:
			if(Common.HIGHDEBUG)
				Log.i(Common.TAG,"Refresh public timeline");
			refreshTimeline();
		}
		return false;
	}

	public void refreshTimeline(){
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"Downloading public timeline");
		findViewById(R.id.listPublicPhotos).setVisibility(View.GONE);
		findViewById(R.id.publicLoadingLinear).setVisibility(View.VISIBLE);
		timelineTask = new GetTimelineTask();
		timelineTask.setActivity(this);
		timelineTask.execute();
	}

	public boolean isThreadRunning() {
		return threadRunning;
	}

	public void setThreadRunning(boolean threadRunning) {
		this.threadRunning = threadRunning;
	}
}
